<template>
  <div id="questionSubmitView">
    <a-form :model="searchParams" layout="inline">
      <a-form-item field="questionId" label="题号" style="min-width: 240px">
        <a-input v-model="searchParams.questionId" placeholder="请输入" />
      </a-form-item>
      <a-form-item field="language" label="编程语言" style="min-width: 240px">
        <a-select
          v-model="searchParams.language"
          :style="{ width: '320px' }"
          placeholder="选择编程语言"
        >
          <a-option>java</a-option>
          <a-option>cpp</a-option>
          <a-option>go</a-option>
          <a-option>html</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="userId" label="提交者" style="min-width: 240px">
        <a-select
          v-model="searchParams.userId"
          :style="{ width: '320px' }"
          placeholder="选择提交者"
          allow-clear
        >
          <a-option
            v-for="option in userOptions"
            :key="option.value"
            :value="option.value"
            :style="{ color: option.color }"
          >
            {{ option.label }}
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="doSubmit">搜索</a-button>
      </a-form-item>
    </a-form>
    <a-divider size="0" />
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
      }"
      @page-change="onPageChange"
    >
      <template #id="{ record }">
        <a-button type="text" @click="showCode(record)">
          {{ record.id }}
        </a-button>
      </template>
      <template #judgeInfo="{ record }">
        <a-tag
          :color="record.judgeInfo?.message === 'Accepted' ? 'green' : 'red'"
        >
          {{ record.judgeInfo?.message }}
        </a-tag>
      </template>
      <template #createTime="{ record }">
        {{ moment(record.createTime).format("YYYY-MM-DD") }}
      </template>
    </a-table>

    <!-- 代码展示对话框 -->
    <a-modal
      v-model:visible="codeModalVisible"
      title="提交代码"
      @cancel="closeCodeModal"
      :footer="false"
      :mask-closable="true"
    >
      <div v-if="currentCode">
        <a-descriptions :column="1">
          <a-descriptions-item label="提交号">{{
            currentCode.id
          }}</a-descriptions-item>
          <a-descriptions-item label="编程语言">{{
            currentCode.language
          }}</a-descriptions-item>
          <a-descriptions-item label="提交时间">{{
            moment(currentCode.createTime).format("YYYY-MM-DD HH:mm:ss")
          }}</a-descriptions-item>
          <a-descriptions-item label="判题结果">
            <a-tag
              :color="
                currentCode.judgeInfo?.message === 'Accepted' ? 'green' : 'red'
              "
            >
              {{ currentCode.judgeInfo?.message }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>
        <a-divider />
        <CodeEditor
          :value="currentCode.code"
          :language="currentCode.language"
          :readonly="true"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import {
  Question,
  QuestionControllerService,
  QuestionSubmitQueryRequest,
  QuestionSubmitVO,
  UserControllerService,
  UserVO,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import moment from "moment";
import CodeEditor from "@/components/CodeEditor.vue";
import { useStore } from "vuex";

const store = useStore();
const tableRef = ref();
const codeModalVisible = ref(false);
const currentCode = ref<QuestionSubmitVO>();

const dataList = ref([]);
const total = ref(0);
const searchParams = ref<QuestionSubmitQueryRequest>({
  questionId: undefined,
  language: undefined,
  pageSize: 10,
  current: 1,
});

// 添加用户列表相关状态
const userList = ref<UserVO[]>([]);
const userOptions = ref<{ label: string; value: number; color?: string }[]>([]);

const loadData = async () => {
  const res = await QuestionControllerService.listQuestionSubmitByPageUsingPost(
    {
      ...searchParams.value,
      sortField: "createTime",
      sortOrder: "descend",
    }
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 获取用户列表
 */
const loadUserList = async () => {
  try {
    const res = await UserControllerService.listUserVoByPageUsingPost({
      pageSize: 20,
      current: 1,
    });
    if (res.code === 0) {
      userList.value = res.data?.records || [];
      userOptions.value = [
        {
          label: "选择自己",
          value: store.state.user.loginUser.id || 0,
          color: "blue",
        },
        ...userList.value.map((user) => ({
          label: user.userName || "",
          value: user.id || 0,
        })),
      ];
    }
  } catch (error) {
    message.error("获取用户列表失败");
  }
};

/**
 * 显示代码
 */
const showCode = async (record: any) => {
  try {
    const res = await QuestionControllerService.getQuestionSubmitCodeUsingGet(
      record.id
    );
    if (res.code === 0) {
      currentCode.value = res.data;
      codeModalVisible.value = true;
    } else {
      message.error("获取代码失败，" + res.message);
    }
  } catch (error) {
    message.error("获取代码失败");
  }
};

/**
 * 关闭代码展示对话框
 */
const closeCodeModal = () => {
  codeModalVisible.value = false;
  currentCode.value = undefined;
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
  loadUserList();
});

const columns = [
  {
    title: "提交号",
    slotName: "id",
  },
  {
    title: "编程语言",
    dataIndex: "language",
  },
  {
    title: "判题信息",
    slotName: "judgeInfo",
  },
  {
    title: "判题状态",
    dataIndex: "status",
  },
  {
    title: "题目 id",
    dataIndex: "questionId",
  },
  {
    title: "提交者",
    dataIndex: "userName",
  },
  {
    title: "创建时间",
    slotName: "createTime",
  },
];

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const router = useRouter();

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (question: Question) => {
  router.push({
    path: `/view/question/${question.id}`,
  });
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};
</script>

<style scoped>
#questionSubmitView {
  max-width: 1280px;
  margin: 0 auto;
}
</style>
